package com.iwhalecloud.citybrain.flow.platform.manager.domain.model;

import com.iwhalecloud.citybrain.flow.platform.manager.domain.enums.NextNodeParamEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.factory.FlowNextNodeAssigneeFactory;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowNodeTempParamRepository;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @author liyang
 */
@Data
@Service
public class FlowNextNodeAssignee implements Serializable, ApplicationContextAware {

    private static final long serialVersionUID = -7750862612450898419L;

    static FlowNodeTempParamRepository flowNodeTempParamRepository;

    /**
     * 参数编号
     */
    private Integer id;

    /**
     * 流程实例编号
     */
    @NotNull(message = "流程实例编号不能为空")
    private String processInstanceId;

    /**
     * 节点编码
     */
    @NotNull(message = "节点编码不能为空")
    private String nodeCode;

    /**
     * 下一节点指定的用户.
     */
    private String nextAssignee;


    public void save() {

        //如果已经存在，则覆盖掉
        List<FlowNodeTempParamDomain> flowNodeTempParamDomainList = flowNodeTempParamRepository.listNodeTempParam(processInstanceId
                ,nodeCode,NextNodeParamEnum.NEXT_NODE_ASSIGNEE);
        if (Objects.nonNull(flowNodeTempParamDomainList) && flowNodeTempParamDomainList.size() > 0){
            flowNodeTempParamDomainList.stream().forEach(flowNodeNextAssignee -> {
                flowNodeNextAssignee.setParamValue(nextAssignee);
                flowNodeNextAssignee.update();
            });
        }else{
            FlowNodeTempParamDomain flowNodeTempParamDomain = new FlowNodeTempParamDomain();
            flowNodeTempParamDomain.setNodeCode(nodeCode);
            flowNodeTempParamDomain.setProcessInstanceId(processInstanceId);
            flowNodeTempParamDomain.setParamCode(NextNodeParamEnum.NEXT_NODE_ASSIGNEE.getCode());
            flowNodeTempParamDomain.setParamValue(nextAssignee);
            flowNodeTempParamDomain.save();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        flowNodeTempParamRepository = applicationContext.getBean(FlowNodeTempParamRepository.class);
    }
}